package com.marvin.spring.intercept.learning.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @ClassName: TimeAspect
 * @Description: Aspect配置
 * @Author Marvin
 * @Date 2019/5/22 23:29
 */
@Slf4j
@Aspect
@Component
public class TimeAspect {

    ///*目标方法调用前执行*/
    //@Before("execution(* com.marvin.spring.intercept.learning.controller.TestController.*(..))")
    //public void doBeforeTimeAspect() {
    //    System.out.println("Aspect： -->time aspect Before");
    //}
    //
    ///*目标方法调用后执行，抛异常仍然执行*/
    //@After("execution(* com.marvin.spring.intercept.learning.controller.TestController.*(..))")
    //public void doAfterTimeAspect() {
    //    System.out.println("Aspect： -->time aspect After");
    //}
    //
    ///*目标方法调用后执行，抛异常不执行*/
    //@AfterReturning("execution(* com.marvin.spring.intercept.learning.controller.TestController.*(..))")
    //public void doAfterReturningTimeAspect() {
    //    System.out.println("Aspect： -->time aspect AfterReturning");
    //}
    //
    ///*目标方法调用抛异常执行*/
    //@AfterThrowing(pointcut="execution(* com.marvin.spring.intercept.learning.controller.TestController.*(..))", throwing = "ex")
    //public void doAfterThrowingTimeAspect(Exception ex) {
    //    System.out.println("Aspect： -->time aspect AfterThrowing, ex is : " + ex);
    //}

    /*环绕通知，结合前面几个通知的特点*/
    @Around("execution(* com.marvin.spring.intercept.learning.controller.TestController.*(..))")
    public Object handleControllerMethod(ProceedingJoinPoint pjp) throws Throwable {
        long start = new Date().getTime();
        log.info("Aspect： -->time aspect start");
        //获取方法参数
        Object[] args = pjp.getArgs();

        log.info("Aspect： -->方法名称：" + pjp.getSignature().getName());
        for (Object arg : args) {
            log.info("Aspect： -->方法参数： args is: " + arg);
        }
        // start stopwatch
        //调用真正的方法
        Object retVal = pjp.proceed();
        log.info("Aspect： -->return is: " + retVal);
        // stop stopwatch
        log.info("Aspect： -->time aspect end ");
        log.info("Aspect： -->Time Aspect finish, used time: " + (new Date().getTime() - start));

        return retVal;
    }
}
